package com.jpcc.vw.onlineRadio.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.RemoteException;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
/*Start by menglingqiang*/
import android.util.Log;
import java.util.Date;
/*End by menglingqiang*/

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.DailyRecommendationAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.bean.AlbumCategoryResultBean;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.ExclusiveRecommendationBean;
import com.jpcc.vw.onlineRadio.model.bean.RecommendationEntity;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.tracelog.TracelogInterface;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action0;

/**
 * 包含媒体推荐、个性推荐、分类所进入的画面所以都是common
 */
public class DailyRecommendationActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.recyclerview_recommendation)
    RecyclerView recyclerview_recommendation;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.swipe_refrsh_online_radio)
    SmartRefreshLayout swipe_refrsh_online_radio;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;

    private DailyRecommendationAdapter adapter;
    private List<RecommendationEntity> datas = new ArrayList<>();
    private IRadio radioModel;

    private String key = "KEY_TYPE";
    private int type = 0;
    private boolean is_refresh = true;
    private long categoryId = 0;
    private String categoryTag = "";
    private int page_index = 1;

    @Override
    public int getLayoutId() {
        return R.layout.layout_recommendation;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        radioModel = new RadioImpl();
        type = getIntent().getIntExtra(key, 0);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DailyRecommendationActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DailyRecommendationActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
//        for (int index = 0; index < 9; index++) {
//            RecommendationEntity local_entity = new RecommendationEntity();
//            datas.add(local_entity);
//        }
        adapter = new DailyRecommendationAdapter(this, datas);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
        recyclerview_recommendation.setLayoutManager(manager);
        recyclerview_recommendation.setAdapter(adapter);
        if (type == 0) {
            GetDailyRecommendations();
            swipe_refrsh_online_radio.setEnableLoadmore(false);
            swipe_refrsh_online_radio.setEnableRefresh(false);
            tv_title.setText(getResources().getString(R.string.string_18));
        } else if (type == 1) {
            swipe_refrsh_online_radio.setEnableLoadmore(true);
            swipe_refrsh_online_radio.setEnableRefresh(false);
            swipe_refrsh_online_radio.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    is_refresh = true;
                    swipe_refrsh_online_radio.setEnableLoadmore(true);
                    GetExclusiveRecommendations();
                }
            });
            swipe_refrsh_online_radio.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    is_refresh = false;
                    GetExclusiveRecommendations();
                }
            });
            is_refresh = true;
            GetExclusiveRecommendations();
            tv_title.setText(getResources().getString(R.string.string_19));
        } else if (type == 2) {
            categoryId = getIntent().getLongExtra("KEY_CATEGORY_ID", 0);
            categoryTag = getIntent().getStringExtra("KEY_CATEGORY_TAG");
            tv_title.setText(categoryTag);
            swipe_refrsh_online_radio.setEnableLoadmore(true);
            swipe_refrsh_online_radio.setEnableRefresh(true);
            swipe_refrsh_online_radio.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    is_refresh = true;
                    swipe_refrsh_online_radio.setEnableLoadmore(true);
                    GetAlbumListByCategory();
                }
            });
            swipe_refrsh_online_radio.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    is_refresh = false;
                    GetAlbumListByCategory();
                }
            });
            is_refresh = true;
            GetAlbumListByCategory();
        }
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    /**
     * 获取个性推荐
     */
    private void GetExclusiveRecommendations() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if(inter != null){
                inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"DEBUG",null,"GetRecommendation request");
            }else {
                Log.e("JPCC","inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetRecommendation(local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
                if(is_refresh){
                    progress_circular.setVisibility(View.VISIBLE);
                }
            }
        }).subscribe(new CommonSubscriber<ExclusiveRecommendationBean>() {
            @Override
            public void onSuccess(ExclusiveRecommendationBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_online_radio.finishRefresh();
                swipe_refrsh_online_radio.finishLoadmore();
                if (Constants.STATUS_SUCCESS_CODE == response.getCode()) {
                    if (response.getData() != null && response.getData().size() > 0) {
                        if (is_refresh) {
                            datas.clear();
                            page_index = 1;
                        }
                        is_refresh = false;
                        tv_show_empty.setVisibility(View.GONE);
                        datas.addAll(response.getData());
                        adapter.setDatas(datas);
                        page_index++;
                    } else {
                        swipe_refrsh_online_radio.finishLoadmore();
                        swipe_refrsh_online_radio.setEnableLoadmore(false);
                        if (is_refresh) {
                            tv_show_empty.setVisibility(View.VISIBLE);
                        }
                    }

                } else {
//                    hideProgress();
                    ToastUtils.show(response.getStatusMessage());
                }

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"DEBUG",response.getStatusCode().toString(),"GetRecommendation onSuccess");
                    }else {
                        Log.e("JPCC","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_online_radio.finishRefresh();
                ToastUtils.show(response.getStatusMessage());
                if (is_refresh) {
                    tv_show_empty.setVisibility(View.VISIBLE);
                }

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"ERROR",response.getStatusCode().toString(),"GetRecommendation onFailure");
                    }else {
                        Log.e("JPCC","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    /**
     * 获取每日推荐
     */
    private void GetDailyRecommendations() {
//        radioModel.GetDailyRecommendations().doOnSubscribe(new Action0() {
//            @Override
//            public void call() {
//                showProgress();
//            }
//        }).subscribe(new CommonSubscriber<DailyRecommendationBean>() {
//            @Override
//            public void onSuccess(DailyRecommendationBean response) {
//                datas.clear();
//                hideProgress();
//                if (Constants.STATUS_SUCCESS_CODE == response.getCode()) {
//                    if (response.getData() != null && response.getData() != null) {
//                        for (DailyRecommendationCategoryBean data : response.getData()) {
//                            datas.addAll(data.getAlbums());
//                        }
//                    }
//                    adapter.setDatas(datas);
//                } else {
//                    ToastUtils.show(response.getStatusMessage());
//                }
//            }
//
//            @Override
//            public void onFailure(BaseBean response) {
//                hideProgress();
//                ToastUtils.show(response.getStatusMessage());
//            }
//        });


    }


    private void GetAlbumListByCategory() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if(inter != null){
                inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"DEBUG",null,"GetAlbumByCategory request");
            }else {
                Log.e("JPCC","inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumByCategory(categoryId, local_page, categoryTag).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
                if(is_refresh){
                    progress_circular.setVisibility(View.VISIBLE);
                }
            }
        }).subscribe(new CommonSubscriber<AlbumCategoryResultBean>() {
            @Override
            public void onSuccess(AlbumCategoryResultBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_online_radio.finishRefresh();
                swipe_refrsh_online_radio.finishLoadmore();
                if ((Constants.STATUS_SUCCESS_CODE == response.getCode()) && (response.getData() != null) && (response.getData().getAlbums() != null) && response.getData().getAlbums().size() > 0) {
                    tv_show_empty.setVisibility(View.GONE);
                    if (is_refresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    datas.addAll(response.getData().getAlbums());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                    page_index++;
                } else {
                    swipe_refrsh_online_radio.finishLoadmore();
                    swipe_refrsh_online_radio.setEnableLoadmore(false);
                }

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"DEBUG",response.getStatusCode().toString(),"GetAlbumByCategory onSuccess");
                    }else {
                        Log.e("JPCC","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_online_radio.finishRefresh();

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),DailyRecommendationActivity.this.getClass().getName(),"ERROR",response.getStatusCode().toString(),"GetAlbumByCategory onFailure");
                    }else {
                        Log.e("jgj","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }
}
